/*
 * @Descripttion: 
 * @version: 
 * @Author: Jinjin
 * @Date: 2022-04-28 10:01:03
 * @LastEditors: Jinjin
 * @LastEditTime: 2022-05-22 15:44:54
 */

//这个文件用来存放关于列表的所有接口

const Router = require('koa-router')
const cognizes = new Router()
const db = require('../util/db')
const bodyparser = require('koa-bodyparser')
cognizes.use(bodyparser())   //调用这个中间件 就可以拿到前端post过来的数据

cognizes.get('/', async (ctx) => {
    ctx.body='认知路由'
})
//写对应的接口
cognizes.get('/cognize', async (ctx) => {
    console.log('---------------------')
    const obj = ctx.query
    var str = 'where '
    for (key in obj) {
        var name = `${key}='${obj[key]}' and `
        str += name
    }
    let searchSql = 'select * from cognize '+str.slice(0,-4)
    let result= await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) {
                throw err;    
            } 
            console.log(data)
            resolve(data)//扔出去一个数组
        })
    })
    ctx.body = result;
    console.log('---------------------')
})
cognizes.get('/*', async (ctx) => {
    console.log('---------------------')
    console.log(ctx.request.url)
    console.log(ctx.request.url.slice(10))
    var table = ctx.request.url.slice(10);
    let searchSql = 'select * from ' + table
    let result= await new Promise((resolve, reject) => {
        return db.query(searchSql, (err, data) => {
            if (err) {
                throw err;    
            } 
            console.log(data)
            resolve(data)//扔出去一个数组
        })
    })
    ctx.body = result;
    console.log('---------------------')
})

module.exports=cognizes